package com.itheima.sh.c_filter_03.loginFilter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter("/hack.html")
public class LoginFilter implements Filter {
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
//        当前过滤器是校验用户是否登录，如果登陆了，那么应该放行，没有登陆，跳转到登陆页面
//        因为登陆了的话，在session对象里有user对象
        User u = (User)request.getSession().getAttribute("u");
        if (u == null){
            //说明session里没有user对象，登陆失败，跳转登陆页面
            response.sendRedirect("/login.html");
        }else{
            //放行
//           response.sendRedirect("/hack.html");
            chain.doFilter(request, response);
        }

    }

    public void init(FilterConfig config) throws ServletException {

    }

}